package com.synjones.handsetS8.fp;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;

import com.synjones.handsetS8.Utils.LogUtil;
import com.synjones.handsetS8.Utils.util;
import com.synjones.handsetS8L.PowerUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by zhaodianbo on 2018-3-23.
 */

public class FindFpModuleAsyncTask extends AsyncTask<Void,Void,Boolean> {
    volatile boolean running=false;
    private ArrayList<String> Supported_VID_PID = new ArrayList();
    String fpModuleType=null;
    Context context;
    private ProgressDialog progressDialog;
    OnFinish onFinish;
    public FindFpModuleAsyncTask(Context context,OnFinish onFinish){
        this.context=context;
        this.onFinish=onFinish;
        //Supported_VID_PID.add("0483:5710");
        Supported_VID_PID.add("0401:542B");
       /* Supported_VID_PID.add("735F:1301");
        Supported_VID_PID.add("735F:1302");
        Supported_VID_PID.add("735F:1303");
        Supported_VID_PID.add("735F:EF01");
        Supported_VID_PID.add("28ED:2043");*/
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        running=true;
        setupProgressDialog("正在连接指纹模块，请稍等", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                PowerUtil.powerFinger ("0");
                PowerUtil.powerUsb("0");
                stopRun();
            }
        });

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        fpModuleType=null;
        int tryCount=0;
        while(running){
            tryCount++;
            LogUtil.d("tryCount="+tryCount);
            PowerUtil.powerFinger ("1");
            PowerUtil.powerUsb("1");
            //util.sleep(2000);
            long t=System.currentTimeMillis();
            while(running){
                LogUtil.d("finding device");
                boolean findFp=findFp();
                if(findFp || System.currentTimeMillis()-t>3000) {
                    LogUtil.d("findFp="+findFp);
                    if(findFp) {
                        running=false;
                        return true;
                    }
                    break;
                }
                util.sleep(100);
            }
            LogUtil.d("closeFingerUSBPower");
            PowerUtil.powerFinger ("0");
            PowerUtil.powerUsb("0");
            util.sleep(500);
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        running=false;

        if(progressDialog!=null){
            progressDialog.dismiss();
        }

        if(result){
            requestPermission();
            return;
        }

        if(onFinish!=null)
            onFinish.onFinish(result,"连接失败");
    }



    public void stopRun(){
        running=false;
        Thread.interrupted();
    }

    private static final String ACTION_USB_PERMISSION = "com.IDWORLD.USB_PERMISSION";
    public void requestPermission() {
        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        UsbDevice usbDevice = enumerateDevice(usbManager);
        if(usbDevice==null) return;
        if (usbManager.hasPermission(usbDevice)) {
            if(onFinish!=null)
                onFinish.onFinish(true,fpModuleType);
        } else {
            PendingIntent comm = PendingIntent.getBroadcast(this.context, 0, new Intent(ACTION_USB_PERMISSION), 0);
            context.registerReceiver(mUsbReceiver, new IntentFilter(ACTION_USB_PERMISSION));
            usbManager.requestPermission(usbDevice, comm);
        }
    }


    private UsbDevice enumerateDevice(UsbManager usbManager) {
        if(usbManager != null) {
            HashMap deviceList = usbManager.getDeviceList();
            if(!deviceList.isEmpty()) {
                StringBuffer sb = new StringBuffer();
                Iterator var4 = deviceList.values().iterator();

                while(true) {
                    while(var4.hasNext()) {
                        UsbDevice device = (UsbDevice)var4.next();
                        if(device.getVendorId() == 0x0401 && device.getProductId() == 0x542B) {
                            return device;
                        }
                    }

                    return null;
                }
            }
        }
        return null;
    }
    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (context) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if(onFinish!=null)
                            onFinish.onFinish(true,fpModuleType);
                    }
                    else {
                        if(onFinish!=null)
                            onFinish.onFinish(false,"授权失败");
                    }
                }
                context.unregisterReceiver(mUsbReceiver);
            }
        }
    };

    void setupProgressDialog(String msg,DialogInterface.OnClickListener listener){
        progressDialog = new ProgressDialog(context, AlertDialog.THEME_HOLO_LIGHT);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(msg);
        progressDialog.setCancelable(false);
        if(listener!=null)
            progressDialog.setButton("取消", listener);
        progressDialog.show();
    }


    private final int VID = 0x2309;
    private final int PID = 0x0606;
    private final int VID3 = 0x28ED;
    private final int PID3 = 0x2043;
    public boolean findFp(){

        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
            if (usbDevice != null && isSupportedDevice(usbDevice)) {
                LogUtil.d("find device");
                int pid=usbDevice.getProductId();
                int vid= usbDevice.getVendorId();

                fpModuleType="ld";
                return true;
            }
        }
        return false;
    }

    public  boolean isSupportedDevice(UsbDevice device) {
        //return device.getProductId() == PL2303HXA_PRODUCT_ID;
        Iterator<String> iterator=Supported_VID_PID.iterator();
        while(iterator.hasNext()){
            if(getDeviceVIDPID(device).equals(iterator.next()))
                return true;
        }
        return false;
    }


    private  String getDeviceVIDPID(UsbDevice d) {
        return String.format("%04X:%04X", new Object[] {Integer.valueOf(d.getVendorId()),
                Integer.valueOf(d.getProductId()) });
    }

    public interface OnFinish{
        void onFinish(boolean result, String value);
    }

}
